<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>JWT 解码器</title>
        <style>
            .flex {
                display: flex;
            }

            .flex-1 {
                flex: 1;
            }

            .ml-1 {
                margin-left: 1em;
            }

            h4:first-child {
                margin-block-start: 0;
            }
        </style>
    </head>
    <body>
        <h1>JWT 解码器</h1>
        <main class="flex">
            <div>
                <textarea
                    name="jwt"
                    id="jwt"
                    cols="40"
                    rows="10"
                    placeholder="输入 JWT"
                ></textarea>
                <br />
                <button id="btn">解码</button>
            </div>

            <div id="output" class="ml-1 flex-1">
                <h4>header</h4>
                <pre id="header">...</pre>
                <h4>payload</h4>
                <pre id="payload">...</pre>
            </div>
        </main>

        <script>
            const $ = (el) => document.querySelector(el);

            $('#btn').addEventListener('click', () => {
                const jwt = $('#jwt').value;
                const [header, payload] = decodeJWT(jwt);
                render('#header', header);
                render('#payload', payload);
            });

            function render(el, data) {
                $(el).innerHTML = JSON.stringify(data, null, 4);
            }

            function decodeJWT(jwt) {
                const tokens = jwt.split('.').slice(0, 2);

                return tokens.map((item) => {
                    const str = window.atob(item);
                    return JSON.parse(str);
                });
            }
        </script>
    </body>
</html>
